﻿using FluentData;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using TaoBaoKe.Common;
using htmlTBK.Models;
namespace FormTBK.Function
{
    public partial class GetKeyFromBD : Form
    {
        public GetKeyFromBD()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }
        IDbContext dbContext = new DbContext().ConnectionString("server=.;User ID=sa;Password=111111;database=test;Connection Reset=FALSE", new SqlServerProvider());
        private void button1_Click(object sender, EventArgs e)
        {
            string cookie = this.tbCookie.Text.Trim();
            string data = this.tbData.Text.Trim();
            int seedId = 0;
            string key = "";
            HtmlWeb w = new HtmlWeb();
            w.OverrideEncoding = Encoding.UTF8;
            w.UseCookies = true;
            w.NeedParse = false;
            w.CookieStr = cookie.Replace(";", ",");
            w.PreRequest += req;
            HtmlAgilityPack.HtmlDocument d;
            string result;
            while (true)
            {
                try
                {


                    tbk_Keyword m = dbContext.Sql("select top 1 * from tbk_Keyword  where  IsUsed=0 and KeywordId>=" + this.tbRecordFrom.Text.Trim() + " and KeywordId<"+this.tbRecordTo.Text.Trim()).QuerySingle<tbk_Keyword>();
                    if (m==null)
                    {
                        MessageBox.Show(this, "未找到数据");
                        return;
                    }
                    seedId = m.KeywordId;
                    key = m.Keyword;
                    this.tbResult.AppendText("当前关键字"+key);
                    key = key.UrlEncode();
                    w.PostData = "sources%5B0%5D=SEARCHAPI&sources%5B1%5D=SEARCHENGINE&sources%5B2%5D=B2C&sources%5B3%5D=CUBEADLIB&negtiveWords=&seedWords=" + key + "&page=1&pageRows=100";
                    d = w.Load("http://tici.cubead.com/open/wordexpand/startExpandWord.json", "post");
                    result = d.Text;
                    MatchCollection mc = result.Matches("\"keyword\":\"(?<key>.*?)\"");
                    if (mc.Count == 0)
                    {
                        this.tbResult.AppendText(Environment.NewLine);
                        this.tbResult.AppendText("没找到信息");
                        dbContext.Sql("update tbk_keyword set isused=1 where KeywordId=" + seedId).Execute();
                    }
                    else
                    {
                        this.tbResult.AppendText(Environment.NewLine);
                        this.tbResult.AppendText("找到" + mc.Count + "个");
                        //for (int i = 0; i < mc.Count; i++)
                        //{
                        //    this.tbResult.AppendText(Environment.NewLine);
                        //    this.tbResult.AppendText(mc[i].Groups["key"].Value);
                        //}
                        for (int i = 0; i < mc.Count; i++)
                        {
                            tbk_KeywordBySeed k = new tbk_KeywordBySeed();
                            k.Keyword = mc[i].Groups["key"].Value;
                            k.SeedId = seedId;
                            dbContext.Insert<tbk_KeywordBySeed>("tbk_KeywordBySeed", k).AutoMap(x => x.Kid).Execute();
                        }
                        Match mcc = result.Match("\"pageCount\":(?<page>.*?),");
                        int page = 1;
                        if (mcc.Success)
                        {
                            this.tbResult.AppendText(Environment.NewLine);
                            page = Convert.ToInt32(mcc.Groups["page"].Value);
                            this.tbResult.AppendText(page.ToString());
                        }
                        if (page > 1)
                        {
                            int tempPage = 2;
                            while (tempPage <= page)
                            {
                                w.PostData = "page=" + tempPage + "&pageRows=100&order=ASC";
                                d = w.Load("http://tici.cubead.com/open/wordexpand/getKEResultByPage.json");
                                result = d.Text;
                                mc = result.Matches("\"keyword\":\"(?<key>.*?)\"");
                                if (mc.Count == 0)
                                {
                                    this.tbResult.AppendText(Environment.NewLine);
                                    this.tbResult.AppendText("没找到信息");
                                }
                                else
                                {
                                    this.tbResult.AppendText(Environment.NewLine);
                                    this.tbResult.AppendText("找到" + mc.Count + "个");
                                    //for (int ii = 0; ii < mc.Count; ii++)
                                    //{
                                    //    this.tbResult.AppendText(Environment.NewLine);
                                    //    this.tbResult.AppendText(mc[ii].Groups["key"].Value);
                                    //}
                                    for (int i = 0; i < mc.Count; i++)
                                    {
                                        tbk_KeywordBySeed k = new tbk_KeywordBySeed();
                                        k.Keyword = mc[i].Groups["key"].Value;
                                        k.SeedId = seedId;
                                        dbContext.Insert<tbk_KeywordBySeed>("tbk_KeywordBySeed", k).AutoMap(x => x.Kid).Execute();
                                    }
                                }
                                tempPage++;
                            }
                        }
                        this.tbResult.AppendText(Environment.NewLine);
                        this.tbResult.AppendText("数据插入完成");
                        this.tbResult.AppendText(Environment.NewLine);
                        dbContext.Sql("update tbk_keyword set isused=1 where KeywordId=" + seedId).Execute();
                        this.tbResult.AppendText("修改seed状态完成");
                        this.tbResult.AppendText(Environment.NewLine);
                        //this.tbResult.AppendText("等待2秒");
                       // this.tbResult.AppendText(Environment.NewLine);
                        //System.Threading.Thread.Sleep(2000);
                    }
                }
                catch (Exception ex)
                {

                    this.tbResult.Clear();
                    this.tbResult.AppendText("异常:" + ex.Message);
                    this.tbResult.AppendText(Environment.NewLine);
                    System.Threading.Thread.Sleep(5000);
                }
            }
            //this.tbResult.Text = result;
        }
        private bool req(System.Net.HttpWebRequest request)
        {
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
            request.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
            request.Headers.Add("Origin", "http://tici.cubead.com");
            request.AutomaticDecompression = DecompressionMethods.GZip;
            request.Host = "tici.cubead.com";
            request.Referer = "http://tici.cubead.com/open/wordexpand/editExpandWord.do";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31";
            return true;
        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void label4_Click(object sender, EventArgs e)
        {

        }

        private void tbrecordNum_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
